﻿Imports Microforma.BEL
Imports Microforma.BLL
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports Atalasoft.Imaging.WinControls
Imports Atalasoft.Imaging
Imports Atalasoft.Imaging.Codec
Imports Atalasoft.Imaging.Codec.Tiff
Imports Atalasoft.Imaging.ImageProcessing
Imports Atalasoft.Imaging.ImageProcessing.Document
Imports Atalasoft.Imaging.ImageProcessing.Effects
Imports Atalasoft.Imaging.ImageProcessing.Filters
Imports Atalasoft.Imaging.ImageProcessing.Transforms
Imports Atalasoft.Imaging.ImageProcessing.Channels
Imports Atalasoft.Imaging.Metadata
Imports Atalasoft.Imaging.Drawing
Imports Atalasoft.Imaging.Codec.Pdf



Public Class frmPanelIndizacion
    Dim IntResolucion As Double
    Dim IntSalida As Integer
    Dim StrFormatoArchivo As String
    Dim BolDuplex As Boolean
    Dim BolDesviacion As Boolean
    Dim BolBlancos As Boolean
    Dim StrIdLote As String
    Dim StrCarpetaLote As String
    Dim BolOCR As Byte

    Private imageChanged As Boolean = False
    Dim cambioImagen As Boolean = False
    Dim currentPage As Int16
    Dim pageCount As Int16
    Dim P_currentFileR As String

    Private Bol_VistaThumbnails As Boolean = True
    Dim escanerBL As EscanerBL
    Dim documentosBL As DocumentosBL
    Dim documentoBE As DocumentosBE

    Public BolModoIndizacion As Boolean
    Dim frmIndizacion As frmIndizarDocumentos


    Private Sub frmEscanearDocs_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Leave

    End Sub

    Private Sub frmEscanearDocs_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        escanerBL = New EscanerBL
        documentosBL = New DocumentosBL
        documentoBE = New DocumentosBE

        g_StrPathDocument = "C:\TEST CREACION DATABASE\MICROFORMADEMO\ImgMICROFORMADEMO\"


        Call CargarConfiguracionEscaner()

        SplitContainerVisorGeneral.Panel1Collapsed = True

        'Carga lotes
        Call CargaLotes()

        Dim pdf As PdfDecoder = New PdfDecoder
        pdf.Resolution = 300
        Atalasoft.Imaging.Codec.RegisteredDecoders.Decoders.Add(pdf)

        If BolModoIndizacion Then
            frmIndizacion = New frmIndizarDocumentos
            frmIndizacion.Show()
        End If

    End Sub
    Sub CargaLotes()

        Dim lotesBl = New LoteBL
        Dim datatableLotes As DataTable = lotesBl.GetListToScan
        Dim lviItem As ListViewItem

        For Each dtrFila As DataRow In datatableLotes.Rows
            lviItem = New ListViewItem
            lviItem.Text = dtrFila("Nombre")
            lviItem.SubItems.Add(dtrFila("documentos"))
            lviItem.SubItems.Add(dtrFila("folios"))
            lviItem.SubItems.Add(dtrFila("idLote"))
            lviItem.SubItems.Add(dtrFila("Cliente"))

            LVLotes.Items.Add(lviItem)
        Next

    End Sub

    Sub CargarConfiguracionEscaner()

        LvConfiguracionEscaner.Items.Clear()

        Dim datableEscaner As DataTable = escanerBL.GetListAll
        Dim lviItem As ListViewItem

        For Each dtrFila As DataRow In datableEscaner.Rows
            lviItem = New ListViewItem
            lviItem.Text = dtrFila("Nombre")

            If (dtrFila("TipoArchivo") = "PDO") Then
                lviItem.SubItems.Add("PDF-OCR")
            Else
                lviItem.SubItems.Add(dtrFila("TipoArchivo"))
            End If

            Select Case dtrFila("Formato")
                Case 0
                    lviItem.SubItems.Add("B/N")
                Case 1
                    lviItem.SubItems.Add("GRIS")
                Case 2
                    lviItem.SubItems.Add("COLOR")
            End Select
            lviItem.SubItems(1).Tag = dtrFila("Formato")

            lviItem.SubItems.Add(dtrFila("Resolucion"))
            lviItem.SubItems.Add(dtrFila("Duplex"))

            lviItem.SubItems.Add(dtrFila("EliminarBlancos"))
            lviItem.SubItems.Add(dtrFila("EliminarDesviacion"))


            lviItem.ToolTipText = dtrFila("Descripcion")

            lviItem.ImageIndex = 1

            LvConfiguracionEscaner.Items.Add(lviItem)
        Next

    End Sub

    Private Sub RadButtonElementVistaThmbnail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementVistaThmbnail.Click
        If Bol_VistaThumbnails Then
            Bol_VistaThumbnails = False
            SplitContainerVisorGeneral.Panel1Collapsed = False
        Else
            Bol_VistaThumbnails = True
            SplitContainerVisorGeneral.Panel1Collapsed = True
        End If
    End Sub


    Private Sub RbtEscanear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RbtEscanear.Click
        PanEscanearOpciones.Visible = True
    End Sub
    Private Sub BtnSeleccionaEscaner_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSeleccionaEscaner.Click
        ' Display TWAIN Select Source dialog
        Call EZTwain.SelectImageSource(System.IntPtr.Zero)
    End Sub

    Private Sub BtnIniciarEscaner_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnIniciarEscaner.Click
        PanEscanearOpciones.Visible = False
        Application.DoEvents()

        Dim TmpRutaImagen As String = g_StrPathDocument

        'Valida formulario
        If Not ValidaFormulario() Then Exit Sub

        StrCarpetaLote = Strings.Right("00000000" & StrIdLote, 8)
        g_StrPathDocument = g_StrPathDocument & StrCarpetaLote
        If Not ExistFile(g_StrPathDocument) Then
            System.IO.Directory.CreateDirectory(g_StrPathDocument)
        End If

        Viewer.AutoZoom = AutoZoomMode.FitToWidth
        ThumbnailView1.LoadMethod = ThumbLoadMethod.WhenVisible
        If BtnMultiple.Checked Then
            Call EscanerPorPagina(-1)
        Else
            Call EscanerPorPagina(TxtCantidad.Text)
        End If
        g_StrPathDocument = TmpRutaImagen
    End Sub
    Sub EscanerPorPagina(ByVal IntCantidadPaginas As Int16)
        Dim fileName As String
        Dim IntcontadorImagenes As Byte
        Dim StrNombreArchivo As String

        Call EZTwain.SetHideUI(True)
        Call EZTwain.SetFileAppendFlag(True)
        If EZTwain.OpenDefaultSource() Then

            Call EZTwain.SetAutoOCR(BolOCR)
            ' Not guaranteed to work, check return = 1
            Call EZTwain.SetPixelType(0)
            Call EZTwain.SetBitDepth(IntSalida)
            Call EZTwain.SetResolution(IntResolucion)
            Call EZTwain.EnableDuplex(BolDuplex)
            Call EZTwain.SetAutoDeskew(IIf(BolDesviacion = True, 1, 0))
            Call EZTwain.SetAutoScan(True)
            Call EZTwain.SetMultiTransfer(True)
            Call EZTwain.SetBlankPageMode(IIf(BolBlancos = True, 1, 0))

            StrNombreArchivo = NuevoNombreArchivo(g_StrPathDocument)
            fileName = g_StrPathDocument & "\" & StrNombreArchivo
            Do
                ' If you can't get a Window handle, use System.IntPtr.Zero:
                If EZTwain.AcquireToFilename(Me.Handle, fileName) <> 0 Then
                    Exit Do
                End If

                Viewer.Open(fileName, IntcontadorImagenes)
                Application.DoEvents()

                IntcontadorImagenes += 1
                If IntcontadorImagenes = IntCantidadPaginas Then
                    Call AgregarDocumento(StrCarpetaLote & "\" & StrNombreArchivo, IntcontadorImagenes, StrNombreArchivo)
                    IntcontadorImagenes = 0
                    StrNombreArchivo = NuevoNombreArchivo(g_StrPathDocument)
                    fileName = g_StrPathDocument & "\" & StrNombreArchivo
                End If
            Loop While Not EZTwain.IsDone()
            If IntcontadorImagenes > 0 Then Call AgregarDocumento(StrCarpetaLote & "\" & StrNombreArchivo, IntcontadorImagenes, StrNombreArchivo)

            Call EZTwain.CloseSource()
        End If
        If EZTwain.LastErrorCode() <> 0 Then
            Call EZTwain.CloseSource()
            Call EZTwain.ReportLastError(EZTwain.LastErrorText)
        End If
    End Sub

    Function AgregarDocumento(ByVal Archivo As String, ByVal Paginas As Byte, ByVal Titulo As String) As Boolean
        Dim ItemEntidad As New DocumentosBE
        ItemEntidad.Archivo = Archivo
        ItemEntidad.IdLote = StrIdLote
        ItemEntidad.Paginas = Paginas
        ItemEntidad.Titulo = Titulo
        documentosBL.Add(ItemEntidad)

        Call AgregarItemGrillaDocumentos(Titulo, Archivo, Paginas, documentosBL.UltimoDocumento)


        Return True
    End Function

    Function ValidaFormulario() As Boolean
        If LvConfiguracionEscaner.SelectedItems.Count = 0 Then
            MessageBox.Show("Seleccione una configuración del escaner.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        Else
            StrFormatoArchivo = LvConfiguracionEscaner.SelectedItems(0).SubItems(1).Text
            IntSalida = LvConfiguracionEscaner.SelectedItems(0).SubItems(1).Tag
            IntResolucion = LvConfiguracionEscaner.SelectedItems(0).SubItems(3).Text
            BolDuplex = LvConfiguracionEscaner.SelectedItems(0).SubItems(4).Text
            BolBlancos = LvConfiguracionEscaner.SelectedItems(0).SubItems(5).Text
            BolDesviacion = LvConfiguracionEscaner.SelectedItems(0).SubItems(6).Text

            If LvConfiguracionEscaner.SelectedItems(0).SubItems(1).Text.IndexOf("OCR") > 0 Then
                BolOCR = 1
                StrFormatoArchivo = "PDF"
            Else
                BolOCR = 0
            End If
        End If

        If LVLotes.SelectedItems.Count = 0 Then
            MessageBox.Show("Seleccione un lote a procesar.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        Else
            StrIdLote = LVLotes.SelectedItems(0).SubItems(3).Text
        End If
        Return True
    End Function
    'Sub EscanearMultipagina()
    '    Dim IntContador As Byte = 1
    '    Dim fileName As String
    '    Dim StrNombreArchivo As String
    '    Call EZTwain.SetHideUI(True)
    '    Call EZTwain.SetFileAppendFlag(False)
    '    If EZTwain.OpenDefaultSource() Then
    '        Call EZTwain.SelectFeeder(True)
    '        Call EZTwain.EnableDuplex(BolDuplex)
    '        ' Not guaranteed to work, check return = 1
    '        Call EZTwain.SetPixelType(0)
    '        Call EZTwain.SetBitDepth(IntSalida)
    '        Call EZTwain.SetResolution(IntResolucion)
    '        Call EZTwain.SetAutoDeskew(IIf(BolDesviacion = True, 1, 0))
    '        ' If you can't get a Window handle, use System.IntPtr.Zero:
    '        StrNombreArchivo = NuevoNombreArchivo(g_StrPathDocument)
    '        fileName = g_StrPathDocument & "\" & StrNombreArchivo
    '        Call EZTwain.AcquireMultipageFile(Me.Handle, fileName)

    '        Viewer.Open(fileName, IntContador + 1)
    '        Call AgregarDocumento(StrCarpetaLote & "\" & StrNombreArchivo, IntContador, StrNombreArchivo)

    '        IntContador += 1
    '    End If
    '    If EZTwain.LastErrorCode() <> 0 Then
    '        EZTwain.CloseSource()
    '        Call EZTwain.ReportLastError(EZTwain.LastErrorText)
    '    End If


    'End Sub
    Function NuevoNombreArchivo(ByVal CarpetaBuscar As String) As String


        Dim root As String = CarpetaBuscar
        Dim dir As New System.IO.DirectoryInfo(root)
        Dim fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories)


        Dim fileQuery = From file In fileList _
                        Where file.Extension = "." & StrFormatoArchivo _
                        Order By file.Name _
                        Select file

        Dim fileQuery2 = From file In fileQuery _
                         Order By file.CreationTime _
                         Select file.Name, file.CreationTime

        ' Execute the query

        If fileQuery2.Count = 0 Then
            Return "00000001." & StrFormatoArchivo
        End If

        Dim newestFile = fileQuery2.Last
        'Reemplaza ultimo Digito
        Dim IntDigito As Integer
        Dim StrNuevoNombre As String
        IntDigito = CInt(newestFile.Name.Replace("." & StrFormatoArchivo, ""))
        StrNuevoNombre = Strings.Right("00000000" & IntDigito + 1, 8) & "." & StrFormatoArchivo

        Return StrNuevoNombre

    End Function
    Private Sub LoadPages(ByVal fileName As String)
        'Copy image to temp file for instert/delete/remove functions.
        ' use the temp file as the current file, so we don't change the opened file
        ' until it is saved.

        'clear the thumb list
        Me.ThumbnailView1.Items.Clear()
        Dim ContadorPaginas As Byte

        ' Use the TiffDecoder for more control and information.
        Dim decoder As TiffDecoder = New TiffDecoder

        'INSTANT VB NOTE: The following 'using' block is replaced by its pre-VB.NET 2005 equivalent:
        '			using (AtalaFileStream fs = New AtalaFileStream(fileName, FileMode.Open, FileAccess.Read))
        Dim fs As AtalaFileStream = New AtalaFileStream(fileName, FileMode.Open, FileAccess.Read)
        Try
            If fs Is Nothing Then
                MessageBox.Show("We were unable to open the file.")
                Return
            End If

            ' Check to see if the file is a valid TIFF.
            If decoder.IsValidFormat(fs) = False Then
                MessageBox.Show("This is not a valid TIFF image.")
                fs.Close()
                Return
            End If

            ' Seek back to the beginning of the file.
            fs.Seek(0, SeekOrigin.Begin)

            ' Get the page count.
            ContadorPaginas = decoder.GetFrameCount(fs)

            fs.Seek(0, SeekOrigin.Begin)



            ' Load thumbs asynchronously and open first page in viewer.
            Me.ThumbnailView1.Asynchronous = True
            Dim i As Integer = 0
            'ORIGINAL LINE: for (int i = 0; i < Me.pageCount; i += 1)
            'INSTANT VB NOTE: This 'for' loop was translated to a VB 'Do While' loop:
            Do While i < ContadorPaginas
                Me.ThumbnailView1.Items.Add(fileName, i, "Página " & (i + 1))
                If i = 0 Then
                    Me.ThumbnailView1.Items(i).Selected = True
                    ' Setting the thumbnail Selected property raises the
                    ' SelectedIndexChanged event.  We load the image there.
                    'Viewer.Image = new AtalaImage(fs, i, null);
                End If
                i += 1
            Loop
            fs.Close()
        Finally
            Dim disp As IDisposable = fs
            disp.Dispose()
        End Try
    End Sub
    Private Sub BtnInterface_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnInterface.Click
        EZTwain.DoSettingsDialog(Me.Handle)

    End Sub
    Private Sub RadToggleButtonElementSeleccionar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadToggleButtonElementSeleccionar.Click
        Viewer.MouseTool = MouseToolType.None
        Me.RadToggleButtonElementSeleccionarRectangulo.ToggleState = Telerik.WinControls.Enumerations.ToggleState.Off
        Me.RadToggleButtonElementSeleccionar.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On
    End Sub
    Private Sub RadToggleButtonElementSeleccionarRectangulo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadToggleButtonElementSeleccionarRectangulo.Click
        'If Control.MouseButtons.Right = Windows.Forms.MouseButtons.Right Then
        Viewer.MouseTool = MouseToolType.Selection
        Viewer.Selection = Me.rectangleSelect

        Me.RadToggleButtonElementSeleccionarRectangulo.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On
        Me.RadToggleButtonElementSeleccionar.ToggleState = Telerik.WinControls.Enumerations.ToggleState.Off

    End Sub
    Private Sub RadButtonElementRecortarArea_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementRecortarArea.Click
        cambioImagen = True
        Me.imageChanged = True

        Try
            ' If there is no selection, display the parameters dialog.
            Dim crop As CropCommand = Nothing
            If Viewer.Selection.Visible Then
                crop = New CropCommand(Viewer.Selection.Bounds)
            Else
                crop = New CropCommand(New Rectangle(New Point(0, 0), Viewer.Image.Size))
                'Dim frm As Form = New Parameters("Crop", crop)
                'If frm.ShowDialog() <> DialogResult.OK Then
                '    frm.Dispose()
                '    Return
                'End If
                'frm.Dispose()
            End If
            Viewer.ApplyCommand(crop, "Crop")
            Me.Viewer.Selection.Visible = False
        Catch ex As Exception

        End Try
    End Sub
    Private Sub RadButtonElementBorrarArea_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementBorrarArea.Click
        Call CopyImageToClipboard(True)
    End Sub
    Private Sub CopyImageToClipboard(ByVal cutArea As Boolean)
        'If _images.Count > 0 Then
        ' Copy to the clipboard and erase that area.
        If Not Viewer.Selection Is Nothing AndAlso Viewer.Selection.Visible AndAlso Viewer.Selection.Bounds.Width > 0 AndAlso Viewer.Selection.Bounds.Height > 0 Then
            ' Crop to the selection.
            'Dim copy As CropCommand = New CropCommand(Viewer.Selection.Bounds)
            'Dim copyImage As AtalaImage = copy.Apply(Viewer.Image).Image
            'copyImage.CopyToClipboard(Me.Handle)

            '' A copy of the image is sent to the clipboard,
            '' so go ahead and distroy this image.
            'copyImage.Dispose()

            If cutArea Then
                ' Erase it by simply drawing a solid region.
                Me.imageChanged = True
                cambioImagen = True
                Viewer.Undos.Add("Borrar Imagen", True)
                Dim myCanvas As Canvas = New Canvas(Viewer.Image)
                myCanvas.DrawRegion(Viewer.Selection.GetRegion(), New SolidFill(Color.White))
                Viewer.Refresh()
            End If
        Else
            Viewer.Image.CopyToClipboard(Me.Handle)

        End If
        ' End If
    End Sub
    Private Sub RadButtonElementAutoEnderezar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementAutoEnderezar.Click
        Me.imageChanged = True
        cambioImagen = True
        Dim autoDeskewCommand As AutoDeskewCommand = New AutoDeskewCommand
        CheckAndApplyCommand(autoDeskewCommand, "AutoDeskewCommand")

    End Sub
    Private Sub RadButtonElementGirarDer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementGirarDer.Click
        Me.imageChanged = True
        cambioImagen = True
        Dim rotate As RotateCommand = New RotateCommand(90)
        CheckAndApplyCommand(rotate, "Undo Rotate 90")
    End Sub
    Private Sub RadButtonElementGirarIzq_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementGirarIzq.Click
        Me.imageChanged = True
        cambioImagen = True
        Dim rotate As RotateCommand = New RotateCommand(270)
        CheckAndApplyCommand(rotate, "Undo Rotate 270")
    End Sub
    Private Sub CheckAndApplyCommand(ByVal cmd As ImageCommand, ByVal name As String)
        If Viewer Is Nothing OrElse Viewer.Image Is Nothing Then
            Return
        End If
        If (Not cmd.IsPixelFormatSupported(Viewer.Image.PixelFormat)) Then
            MessageBox.Show(cmd.GetType().Name & " No se puede aplicar los cambios a este tipo de imagen. " & System.Enum.GetName(GetType(PixelFormat), Viewer.Image.PixelFormat) & ".")
        Else
            Viewer.ApplyCommand(cmd, name)
        End If
    End Sub
    Private Sub RadButtonElementGuardarArchivo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementGuardarArchivo.Click
        Try

            'Call MessageBox.Show("El documento " & Viewer. & " se guardó correctamente.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
            'Me.RadLabelCambiosFile.Text = "El archivo " & SoloNombreConExtensionFile & " se grabo correctamente."
            'timer1.Enabled = True
        Catch ex As Exception

        End Try

    End Sub
    Private Sub RadButtonElementInvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementInvert.Click
        Me.imageChanged = True
        cambioImagen = True
        Dim invert As InvertCommand = New InvertCommand
        CheckAndApplyCommand(invert, "Undo Invert")

    End Sub
    Private Sub RadButtonElementQuitarManchas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementQuitarManchas.Click
        Me.imageChanged = True
        cambioImagen = True
        Dim despeckle As DocumentDespeckleCommand = New DocumentDespeckleCommand
        If Not Viewer.Selection Is Nothing AndAlso Viewer.Selection.Visible Then
            despeckle.RegionOfInterest = New RegionOfInterest(Viewer.Selection.GetRegion())
        End If
        CheckAndApplyCommand(despeckle, "Despeckle")

    End Sub
    Private Sub RadButtonElementRemoverBordes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementRemoverBordes.Click
        Me.imageChanged = True
        cambioImagen = True
        If Not Me.Viewer.Image Is Nothing Then
            Dim cmd As BorderRemovalCommand = New BorderRemovalCommand(BorderRemovalEdges.AllSides, 10, False)
            CheckAndApplyCommand(cmd, "Border Removal")
        End If

    End Sub
    Private Sub RadButtonElementRemoverDefectos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementRemoverDefectos.Click
        Me.imageChanged = True
        cambioImagen = True
        Dim median As DocumentMedianCommand = New DocumentMedianCommand(5)
        If Not Viewer.Selection Is Nothing AndAlso Viewer.Selection.Visible Then
            median.RegionOfInterest = New RegionOfInterest(Viewer.Selection.GetRegion())
        End If
        CheckAndApplyCommand(median, "Remove Noise")

    End Sub
    Private Sub BtnRemoverHuecos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnRemoverHuecos.Click
        Me.imageChanged = True
        cambioImagen = True
        If Not Me.Viewer.Image Is Nothing Then
            Dim cmd As HolePunchRemovalCommand = New HolePunchRemovalCommand()
            CheckAndApplyCommand(cmd, "Hole Punch")
        End If

    End Sub
    Private Sub RadButtonElementDeshacer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementDeshacer.Click
        Viewer.Undos.Undo()
    End Sub
    Private Sub RadButtonElementRehacer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementRehacer.Click
        Viewer.Undos.Redo()
    End Sub
    Private Sub RadButtonElementAjusteOriginal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementAjusteOriginal.Click
        Viewer.AutoZoom = AutoZoomMode.None
        If 0 = AutoZoomMode.None Then Viewer.Zoom = 1
    End Sub
    Private Sub RadButtonElementAjusteOptimo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementAjusteOptimo.Click
        Viewer.AutoZoom = AutoZoomMode.BestFit
        Viewer.Refresh()
    End Sub
    Private Sub RadButtonElementAjustarAlto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementAjustarAlto.Click
        Viewer.AutoZoom = AutoZoomMode.FitToHeight
        Viewer.Refresh()
    End Sub
    Private Sub RadButtonElementAjustarAncho_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButtonElementAjustarAncho.Click
        Viewer.AutoZoom = AutoZoomMode.FitToWidth
        Viewer.Refresh()
    End Sub

    Private Sub LVLotes_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LVLotes.SelectedIndexChanged
        If LVLotes.SelectedItems.Count = 0 Then Exit Sub
        Call CargaDocumentoLote(LVLotes.SelectedItems(0).SubItems(3).Text)

    End Sub
    Sub CargaDocumentoLote(ByVal IDLote As Integer)
        LvEscaneos.Items.Clear()

        Dim datableEscaner As DataTable = documentosBL.List(IDLote)

        For Each dtrFila As DataRow In datableEscaner.Rows
            AgregarItemGrillaDocumentos(dtrFila("Titulo"), dtrFila("RutaArchivo"), _
                                        dtrFila("Paginas"), dtrFila("IdDocumento"))
        Next
    End Sub
    Sub AgregarItemGrillaDocumentos(ByVal Titulo As String, ByVal Archivo As String, _
                                    ByVal Paginas As String, ByVal IdDocuemento As String)
        Dim lviItem As ListViewItem
        lviItem = New ListViewItem
        lviItem.Text = Titulo
        lviItem.SubItems.Add(Archivo)
        lviItem.SubItems.Add(Paginas)
        lviItem.SubItems.Add(IdDocuemento)
        lviItem.ImageIndex = 1
        lviItem.Tag = Archivo
        LvEscaneos.Items.Add(lviItem)
        LvEscaneos.EnsureVisible(LvEscaneos.Items.Count - 1)
    End Sub

    Private Sub LvEscaneos_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles LvEscaneos.DoubleClick
        If LvEscaneos.SelectedItems.Count = 0 Then Exit Sub

        Viewer.Open(g_StrPathDocument & LvEscaneos.SelectedItems(0).SubItems(1).Text)

    End Sub

    Private Sub LvEscaneos_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvEscaneos.SelectedIndexChanged
        If LvEscaneos.SelectedItems.Count = 0 Then Exit Sub

        P_currentFileR = g_StrPathDocument & LvEscaneos.SelectedItems(0).SubItems(1).Text

        Viewer.Open(P_currentFileR, 0)
        pageCount = LvEscaneos.SelectedItems(0).SubItems(2).Text

        If BolModoIndizacion Then
            frmIndizacion.PubIdDocumento = LvEscaneos.SelectedItems(0).SubItems(3).Text

        End If

    End Sub

    Private Sub BtnPaginaAnterior_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPaginaAnterior.Click
        If Me.currentPage > 1 Then
            'load the next page from the file
            Me.currentPage -= 1
            Viewer.Open(P_currentFileR, Me.currentPage - 1)
            ' change thumnail selection.
            'Me.ThumbnailView1.Items(Me.currentPage).Selected = False
            'Me.ThumbnailView1.Items(Me.currentPage - 1).Selected = True
            'Me.ThumbnailView1.EnsureVisible(Me.currentPage - 1)
        End If
    End Sub

    Private Sub BtnPaginaSiguiente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPaginaSiguiente.Click
        If Me.currentPage < Me.pageCount Then
            'load the next page from the file
            Me.currentPage += 1
            Viewer.Open(P_currentFileR, Me.currentPage - 1)
            ' change thumnail selection.
            'Me.ThumbnailView1.Items(Me.currentPage - 2).Selected = False
            'Me.ThumbnailView1.Items(Me.currentPage - 1).Selected = True
            'Me.ThumbnailView1.EnsureVisible(Me.currentPage - 1)
        End If
    End Sub

    Private Sub LvConfiguracionEscaner_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvConfiguracionEscaner.SelectedIndexChanged

    End Sub

    Private Sub Viewer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Viewer.Click

    End Sub
End Class